package com.example.maxboxtwo.utils.listeners;

import android.content.Context;
import android.hardware.camera2.CameraAccessException;
import android.hardware.camera2.CameraManager;
import android.os.Build;
import android.view.View;
import android.widget.ImageView;

import androidx.annotation.RequiresApi;

import com.example.maxboxtwo.R;
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class LightListener implements View.OnClickListener {
    private ImageView imageView;
    private boolean on_off = false;
    private CameraManager cameraManager;
    public LightListener(ImageView lightView,Context context) {
        this.imageView = lightView;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            cameraManager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void onClick(View v) {
    on_off = !on_off;
        if (on_off){
                try {
                    imageView.setBackgroundResource(R.drawable.flashlight_level3);
                    cameraManager.setTorchMode(cameraManager.getCameraIdList()[0],true);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
        }else{
            try {
                imageView.setBackgroundResource(R.drawable.flashlight_level0);
                cameraManager.setTorchMode(cameraManager.getCameraIdList()[0],false);
            } catch (CameraAccessException e) {
                e.printStackTrace();
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    //close the light
    public void closeLight(){
        try {
            imageView.setBackgroundResource(R.drawable.flashlight_level0);
            cameraManager.setTorchMode(cameraManager.getCameraIdList()[0],false);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }
}
